<template>
  <section class="todoapp">
    <!-- 这里放header -->
    <TodoHeader @add="handleAdd"></TodoHeader>
    <!-- 这里放 main 内容区 -->
    <TodoMain :list="list2" @del="handleDel" @state="handleState"   @changeAll="handleAll"></TodoMain>
    <!-- 这里放footer -->
    <TodoFooter :flag="flag"
    :list="list" @delCompleted="clearCompleted"
     @changeFlag="val => {flag = val}"></TodoFooter>
  </section>
</template>

<script>
// 导入三个组件
import TodoHeader from '@/components/TodoHeader.vue'
import TodoMain from '@/components/TodoMain.vue'
import TodoFooter from '@/components/TodoFooter.vue'
export default {
  // 注册组件
  components: { TodoHeader, TodoMain, TodoFooter },
  data() {
    return {
//       list: [
//   { id: 12, name: '吃饭', isDone: false },
//   { id: 14, name: '听歌', isDone: true },
//   { id: 23, name: '洗澡', isDone: true },
//   { id: 34, name: '睡觉', isDone: false },
//   { id: 35, name: '游戏', isDone: false },
// ],
 list: JSON.parse(localStorage.getItem('todo')) || [],
flag:1
    }
  },
  methods:{
    handleDel(id){
      this.list =this.list.filter(item=>item.id !== id)
    },
     handleAdd (todoname) {
      // console.log(todoname)
      this.list.unshift({ 
        id: Date.now(), 
        name: todoname, 
        isDone: false 
      })
    },
    handleState(id){
      // console.log(id);
       const row = this.list.find(item => item.id === id)
  row.isDone = !row.isDone
    },
clearCompleted(){
  this.list = this.list.filter(item=>item.isDone ===false)
},
 handleAll (val) {
      // console.log(val)
      this.list.forEach(item => {
        item.isDone = val
      })
    },
// 计算属性
computed: {
  list2 () {
    if (this.flag === '1') {
      return this.list
    } else if (this.flag === '2') {
      return this.list.filter(item => item.isDone === false)
    } else {
      return this.list.filter(item => item.isDone)
    }
  }
}
  },
  // 侦听器
  watch: {
    list: {
      handler (val) {
        localStorage.setItem('todo', JSON.stringify(val))
      },
      deep: true
    }
  }
}

</script>

<style></style>